package com.jinghua.treatment.controller;

import com.jinghua.treatment.common.GlobalConstant;
import com.jinghua.treatment.common.controller.BaseController;
import com.jinghua.treatment.common.domain.JSONResult;
import com.jinghua.treatment.common.exception.BizException;
import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.entity.SysDoctorNoticeSetting;
import com.jinghua.treatment.entity.SysWechatAccount;
import com.jinghua.treatment.entity.vo.DoctorVO;
import com.jinghua.treatment.service.*;
import com.jinghua.treatment.tools.DateUtil;
import com.jinghua.treatment.tools.StringUtil;
import com.jinghua.treatment.wechat.biz.SMSBiz;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/d/doctor")
public class SysDoctorController extends BaseController {

    @ApiOperation(value = "医生注册")
    @RequestMapping(value = "/doctorRegist", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult doctorRegist(String phone, String smsCode, String docName,String wid) {
        String regSMS = (String) session.getAttribute("regSMS");
        JSONResult result = null;
        if (regSMS != null && regSMS.equals(smsCode)) {
            SysDoctor sysDoctor = sysDoctorService.findByPhone(phone);
            if (sysDoctor != null) {
                result = jsonResult(GlobalConstant.FAIL_CODE, "该号码已经注册", null);
            } else {
                sysDoctor = sysDoctorService.docRegiste(phone, docName,wid);
                session.setAttribute("currentDoctor",sysDoctor);
                // TODO 将来权限做完后 这里要修改
                result = jsonResult(GlobalConstant.SUCCESS_CODE, "ok", "/mod-page/doctor_home.html?doctorId="+sysDoctor.getDoctorId());
            }
        } else {
            result = jsonResult(GlobalConstant.FAIL_CODE, "验证码错误", null);
        }
        return result;
    }

    @ApiOperation(value = "发送注册短信")
    @RequestMapping(value = "/regSMS", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult validateSMS(String phone) {
        if(StringUtils.isEmpty(phone))
            throw new BizException("电话不能为空！");
        String regCode = smsBiz.sendSMSValicode(phone);
        // TODO 需要加过期时间
        session.setAttribute("regSMS", regCode);
        return jsonResult(GlobalConstant.SUCCESS_CODE, "ok", null);
    }

    @ApiOperation(value = "检查医生认证情况")
    @RequestMapping(value = "/checkCertificateStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult checkCertificateStatus(Integer doctorId) {
        doctorId = 39;
        if(StringUtils.isEmpty(doctorId))
            throw new BizException("参数丢失");
        //SysDoctor sysDoctor = (SysDoctor)request.getSession().getAttribute("currentDoctor");

        int result  = sysDoctorService.checkAuthStatus(doctorId,request.getSession());
        SysDoctor sysDoctor = sysDoctorService.findById(doctorId);
        sysDoctor.setIsauthentication(result);
        return jsonResult(GlobalConstant.SUCCESS_CODE, "ok", sysDoctor);
    }


    @ApiOperation(value = "患者关注，返回jsp页面")
    @RequestMapping(value = "/followDoctor", method = {RequestMethod.GET, RequestMethod.POST})
    public String followDoctor(Integer doctorId,Model model) {
       /* SysDoctor sysDoctor = (SysDoctor)request.getSession().getAttribute("currentDoctor");*/
        if(StringUtils.isEmpty(doctorId))
            throw new BizException("参数丢失");
        SysDoctor sysDoctor =sysDoctorService.findById(doctorId);
        model.addAttribute("doctor",sysDoctor);
        SysWechatAccount example  = new SysWechatAccount();
        example.setOpenid(sysDoctor.getWechat());
        example =    sysWechatAccountService.findByExample(example);
        model.addAttribute("wechat",example);
        return "doctor/add_patient";
    }

    @ApiOperation(value = "获取当前医生信息")
    @RequestMapping(value = "/getDoctorInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult getDoctorInfo(Integer doctorId){
        System.out.println("-------- 获取医生个人信息 -------");
        //先从sesison 中取，session 没有 从前台id 取
        SysDoctor sysDoctor = (SysDoctor)session.getAttribute("currentDoctor");
        if(sysDoctor==null&&doctorId!=null){
            sysDoctor = sysDoctorService.findById(doctorId);
        }
        if(sysDoctor.getBirthday()!=null)
            sysDoctor.setAge(DateUtil.getAgeByBirth(sysDoctor.getBirthday()));

        sysDoctor.setNotice(noticeService.selectByDoctorId(doctorId));

        sysDoctor.setClinic(clinicService.selectById(doctorId).get(0));
        return jsonResult(GlobalConstant.SUCCESS_MSG,"ok",sysDoctor);
    }

    @ApiOperation(value = "获取当前医生信息")
    @RequestMapping(value = "/getDoctorInfoById", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult getDoctorInfoById(Integer doctorId){
        System.out.println("-------- 获取医生个人信息 -------");
        SysDoctor sysDoctor  = sysDoctorService.findById(doctorId);
        return jsonResult(GlobalConstant.SUCCESS_MSG,"ok",sysDoctor);
    }


    @ApiOperation(value = "头像上传")
    @RequestMapping(value = "/avatarUpload", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String avatarUpload(@RequestParam("img") MultipartFile img){
        String path = session.getServletContext().getRealPath("/uploads");
        try {
            InputStream is  = img.getInputStream();
            String fileName = StringUtil.mkFileName("jpg");
            FileOutputStream fos  = new FileOutputStream(path+"/"+fileName);
            byte data[]  = new byte[1024];
            int readed = 0;
            while((readed=is.read(data))>0){
                fos.write(data,0,readed);
            }
            is.close();
            fos.close();
            session.setAttribute("avatar",fileName);
            String json = "{\"status\":\"success\",\"url\":\"/uploads/"+fileName+"\"}";
            // return jsonResult(GlobalConstant.SUCCESS_MSG,"ok",fileName);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    @ApiOperation(value = "认证资料上传")
    @RequestMapping(value = "/uploadSertificate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult uploadSertificate(DoctorVO doctorVO){
        //处理头像 和 身份证图片
        String appPath = session.getServletContext().getRealPath("/uploads");
       if(!doctorVO.getAvatar().isEmpty()){
            String avatarPath = uploadImge(doctorVO.getAvatar(),appPath,"avatar");
            doctorVO.setAvatarPath(avatarPath);
        }
        if(!doctorVO.getIdImage().isEmpty()){
            String idImagePath = uploadImge(doctorVO.getIdImage(),appPath,"idcard");
            doctorVO.setIdImagePath(idImagePath);
        }
        sysDoctorService.saveSertificate(doctorVO);
        return jsonResult(GlobalConstant.SUCCESS_CODE,"ok",null);
    }

    @ApiOperation(value = "获取当前登录医生id")
    @RequestMapping(value = "/currentDoctorId", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult currentDoctorId(){
        SysDoctor sysDoctor  = (SysDoctor)session.getAttribute("currentDoctor");
        if(sysDoctor==null)
            throw new BizException("未识别出当前医生");
        return jsonResult(GlobalConstant.SUCCESS_CODE,"ok",sysDoctor.getDoctorId());
    }

    @ApiOperation(value = "加载医生设置和说明")
    @RequestMapping(value = "/loadDoctorSetting", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONResult loadDoctorSetting(Integer doctorId){
        if(StringUtils.isEmpty(doctorId))
            throw new BizException("参数丢失");
        SysDoctorNoticeSetting sysDoctorNoticeSetting = doctorNoticeSettingService.findNoticeSettingByDoctorId(doctorId);
        return jsonResult(GlobalConstant.SUCCESS_CODE,"ok",sysDoctorNoticeSetting);
    }

    @Autowired
    private SMSBiz smsBiz;
    @Autowired
    private SysDoctorService sysDoctorService;

    @Autowired
    private SysWechatAccountService sysWechatAccountService;

    @Resource
    private SysNoticeSettingService noticeService; // 公告业务对象

    @Resource
    private SysClinicService clinicService; // 门诊信息业务对象
    @Autowired
    private DoctorNoticeSettingService doctorNoticeSettingService;
}
